<?php

namespace app\v1\controller;
use support\Request;
use EasyWeChat\Factory;
use app\model\UserModel;
use app\model\CompanyModel;
use app\model\BizAdminModel;
use app\model\BizModel;
use app\model\CardUserModel;
use app\model\PayQrcodeRecordModel;
use app\model\BizGoodsTicketModel;
use app\model\OrderModel;
use Exception;

class UserController
{
    /**
     * 用户授权（微信小程序）
     * @param \support\Request $request
     * @return mixed
     */
    public function init(Request $request){
        $code = $request->post('code');

        $config  = config('wechat.mini_app');
        $app = Factory::miniProgram($config);

        $session = $app->auth->session($code);
        $openid = $session['openid'];

        $user = UserModel::where('open_id', $openid)->first();
        if(!$user){
            $user = new UserModel();
            $user->open_id = $openid;
            $user->created_at = time();
            $user->updated_at = time();
            $user->save();
        }

        if(empty($user->access_token)){
            $token = md5($user->id . time() . $user->openid); 
            $user->access_token = $token;
            $user->save();
        }
        

        return json([
            'code'=>1,
            'data'=>[
                'token'=>$user->access_token,
                'user'=>[
                    'id'=>$user->id,
                    'phone'=>$user->phone,
                    'nickname'=>$user->nickname,
                    'headimg'=>$user->headimg
                ]
            ],
        ]);
    }

    /**
     * 绑定手机号（微信小程序）
     * @param \support\Request $request
     * @return mixed
     */
    public function bindPhone(Request $request){
        try {
            $code = $request->post('code');
            $encryptedData = $request->post('encryptedData');
            $iv = $request->post('iv');
            $user = $request->userLogin;

            if (!$code || !$encryptedData || !$iv) {
                return json([
                    'code' => 0,
                    'message' => '参数不完整'
                ]);
            }

            

            // 获取微信配置
            $config = config('wechat.mini_app');
            $app = Factory::miniProgram($config);

            $result = $app->phone_number->getUserPhoneNumber($code);
		    $phoneNumber = $result['phone_info']['phoneNumber'];

            // 检查手机号是否已被其他用户绑定
            $existingUser = UserModel::where('phone', $phoneNumber)
                ->where('id', '!=', $user->id)
                ->first();
            
            if ($existingUser) {
                return json([
                    'code' => 0,
                    'message' => '该手机号已被其他用户绑定'
                ]);
            }

            // 更新用户手机号
            $user->phone = $phoneNumber;
            $user->updated_at = time();
            $user->save();

            if($user->company_id > 0){
                $company = CompanyModel::find($user->company_id);
                $user['company_name'] = $company->name;
            }

            return json([
                'code' => 1,
                'message' => '手机号绑定成功',
                'data' => [
                    'phone' => $phoneNumber,
                    'user' => $user
                ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'message' => '绑定失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 修改手机号（微信小程序）
     * @param \support\Request $request
     * @return mixed
     */
    public function updatePhone(Request $request){
        try {
            $code = $request->post('code');
            $encryptedData = $request->post('encryptedData');
            $iv = $request->post('iv');

            $user = $request->userLogin;

            if (!$code || !$encryptedData || !$iv) {
                return json([
                    'code' => 0,
                    'message' => '参数不完整'
                ]);
            }

            // 获取微信配置
            $config = config('wechat.mini_app');
            $app = Factory::miniProgram($config);

            $result = $app->phone_number->getUserPhoneNumber($code);
		    $phoneNumber = $result['phone_info']['phoneNumber'];

            // 检查手机号是否已被其他用户绑定
            $existingUser = UserModel::where('phone', $phoneNumber)
                ->where('id', '!=', $user->id)
                ->first();
            
            if ($existingUser) {
                return json([
                    'code' => 0,
                    'message' => '该手机号已被其他用户绑定'
                ]);
            }

            // 更新用户手机号
            $user->phone = $phoneNumber;
            $user->updated_at = time();
            $user->save();

            return json([
                'code' => 1,
                'message' => '手机号修改成功',
                'data' => [
                    'phone' => $phoneNumber,
                    'user' => $user
                ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'message' => '修改失败：' . $e->getMessage()
            ]);
        }
    }

    public function profile(Request $request){
        $user = $request->userLogin;

        if($user->company_id > 0){
            $company = CompanyModel::find($user->company_id);
            if($company){
                $user['company_name'] = $company->name;
            }
        }

        // 云豆总额
        $cardScoreTotal = CardUserModel::where('user_id', $user->id)->sum('score');
        $user['score_total'] = round(($cardScoreTotal + $user->score),2);
        $user['card_score_total'] = round($cardScoreTotal,2);

        // 福利卡数量
        $cardCount = CardUserModel::where('user_id', $user->id)
        ->where('score','>',0)->count();
        $user['card_count'] = $cardCount;

        $user['headimg'] = $user->headimg;
        $user['headimg_url'] = $user->headimgToUrl();

        // 处理性别字段，转换为中文显示
        if (isset($user['sex'])) {
            $sexMap = [0 => '女', 1 => '男'];
            $user['sex_text'] = $sexMap[$user['sex']] ?? '未知';
        }

        // 处理生日字段，转换为标准格式
        if (isset($user['birthday']) && $user['birthday']) {
            $user['birthday_formatted'] = date('Y-m-d', strtotime($user['birthday']));
        }

        // 未核销
        $unConsumeTicketTotal = BizGoodsTicketModel::where('user_id', $user->id)
            ->where('status', '=', BizGoodsTicketModel::STATUS_UNUSED)
            ->where('expired_at','>',time())->count();
        $user['un_consume_ticket_total'] = $unConsumeTicketTotal;

        $user['is_vip'] = $user->isVip();
        $user['had_bind_phone'] = !empty($user['phone']);

        $user['un_get_order_total'] = OrderModel::where('user_id', '=',$user->id)
            ->where('status', '=', 2)
            ->where('pay_status','=',1)
            ->count();

        return json([
            'code' => 1,
            'data' => $user
        ]);
    }

    public function manageBizs(Request $request){
        $user = $request->userLogin;

        $adminBiz = BizAdminModel::where('user_id', $user->id)->first();
        $data = false;
        if($adminBiz){
            $biz = BizModel::find($adminBiz->biz_id);
            $data = [
                'biz_id' => $biz->id,
                'biz_name' => $biz->name,
                'role' => $adminBiz->role
            ];
        }

        return json([
            'code' => 1,
            'data' => $data
        ]);
    }

    /**
     * 设置支付密码
     * @param \support\Request $request
     * @return \support\Response
     */
    public function setPayPassword(Request $request)
    {
        $user = $request->userLogin;
        $payPassword = $request->post('pay_password');
        $code = $request->post('code',null);

        // 校验密码格式：6位数字
        if (!preg_match('/^\\d{6}$/', $payPassword)) {
            return json([
                'code' => 0,
                'message' => '支付密码必须为6位数字'
            ]);
        }

        if(!empty($code)){
            // 验证码 
            // TODO: 验证码验证
        }

        // 加密存储（md5）
        $user->pay_password = md5($payPassword);
        $user->updated_at = time();
        $user->save();

        return json([
            'code' => 1,
            'message' => '支付密码设置成功'
        ]);
    }

    public function sendCode(Request $request){
        $user = $request->userLogin;

        $code = rand(100000, 999999);


        return json([
            'code' => 1,
            'data'=>$code,
            'message' => '验证码发送成功'
        ]);
    }

    public function changePassword(Request $request){
        $user = $request->userLogin;
        $password = $request->post('password');
        $code = $request->post('code');
        
        $user->pay_password = md5($password);
        $user->updated_at = time();
        $user->save();

        return json([
            'code' => 1,
            'message' => '密码修改成功'
        ]);
    }   

    /**
     * 更新头像
     * @param \support\Request $request
     * @return \support\Response
     */ 
    public function updateAvatar(Request $request){
        $user = $request->userLogin;
        $avatar = $request->post('avatar');
        
        $user->headimg = $avatar;
        $user->updated_at = time();
        $user->save();

        return json([
            'code' => 1,
            'message' => '头像更新成功'
        ]);
    }

    public function updateProfile(Request $request){
        $user = $request->userLogin;
        $data = $request->post();

        $user->nickname = $data['nickname'];
        $user->headimg = $data['headimg'];
        
        // 更新性别字段
        if (isset($data['sex'])) {
            $user->sex = $data['sex'];
        }
        
        // 更新生日字段
        if (isset($data['birthday'])) {
            $user->birthday = $data['birthday'];
        }
        
        $user->updated_at = time();
        $user->save();

        return json([
            'code' => 1,
            'message' => '更新成功'
        ]);
    }

    public function generateQrcodeRecord(Request $request){
        $user = $request->userLogin;

        $qrcodeRecord = new PayQrcodeRecordModel();
        $qrcodeRecord->user_id = $user->id;
        $qrcodeRecord->code = substr(md5(time() . $user->id), 8, 16);;
        $qrcodeRecord->created_at = time();
        $qrcodeRecord->updated_at = time();
        $qrcodeRecord->expired_at = time() + 60;
        $qrcodeRecord->save();


        return json([
            'code' => 1,
            'data' => [
                'code' => strtoupper(implode(' ', str_split($qrcodeRecord->code, 4))),
                'expired_at_txt' => date('Y-m-d H:i:s', $qrcodeRecord->expired_at),
                'time' => $qrcodeRecord->expired_at - time(),
                'qrcode_id' => $qrcodeRecord->id
            ]
        ]);
    }

    /**
     * 我的余额和卡列表及折扣
     * @param \support\Request $request
     * @return mixed
     */
    public function balance(Request $request){
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }

            // 检查用户是否已绑定手机号
            if (empty($user['phone'])) {
                throw new Exception('请先绑定手机号');
            }

            // 积分余额
            $userScore = $user->score ?? 0;

            // 我的福利卡余额
            $userCardScoreTotal = CardUserModel::where('user_id', $user->id)
            ->where('expired_at','>',time())
            ->where('score','>',0)
            ->orderBy('expired_at','asc')
            ->sum('score');

            $discount = 100;
            if($user->isVip()){
                $discount = 95;
            }

            return json([
                'code' => 1,
                'data' => [
                    'user_score' => $userScore,
                    'discount' => $discount,
                    'user_card_score_total' => $userCardScoreTotal
                ]
            ]);
        }catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 判断用户是否设置支付密码
     * @param \support\Request $request
     * @return \support\Response
     */
    public function isSetPayPassword(Request $request){
        $user = $request->userLogin;

        return json([
            'code' => 1,
            'data' => !empty($user->pay_password)
        ]);
    }

    public function setUnInputPayPassword(Request $request){
        $user = $request->userLogin;
        $user->un_input_pay_password = $user->un_input_pay_password == 0 ? 1 : 0;
        $user->updated_at = time();
        $user->save();

        return json([
            'code' => 1,
            'message' => $user->un_input_pay_password == 1 ? '开启免密成功' : '关闭免密成功'
        ]);
    }
}
